<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/7/28
 * Time: 16:25
 * Content 打劫
 */

namespace app\alliance\controller;


use app\service\IGeTuiService;
use app\service\MemberService;
use app\service\TaskService;
use Redis\Redis;
use think\Db;

class Robbery extends Common
{
    /**
     * @return array
     * @throws \think\Exception
     * @content 打劫结束  (成功/失败)
     */
    function robberyOver()
    {
        $info = input('post.info');
        if (!empty($info)) {
            $redis = new Redis();
            # 打劫人
//            $robberyInfo = $redis->hGetJson('Robbery', $this->code);
//            if (empty($robberyInfo)) {
            $robberyInfo = $info;
//            }
            # 判断状态
            if ($info['status'] == 1) {
                # 打劫成功
                # 被打劫扣金币,积分
                Db::query("update member_property set gold = gold - " . $robberyInfo['gold_num'] .
                    ",integral=integral-" . $robberyInfo['integral_num'] . " where member_code = '" . $robberyInfo['robbed_code'] . "'");
                # 打劫的人加积分
                Db::query("update member_property set gold = gold + " . $robberyInfo['gold_num'] .
                    ",income = income + " . $robberyInfo['gold_num'] . ",integral=integral+" . $robberyInfo['integral_num'] . " where member_code = '" . $this->code . "'");
                # 增加打劫记录
                Db::table('log_rob')->insert(array(
                    'member_code' => $this->code,
                    'robbed_code' => $robberyInfo['robbed_code'],
                    'create_time' => $info['create_time'],
                    'status' => 1,
                    'gold_num' => $robberyInfo['gold_num'],
                    'integral_num' => $robberyInfo['integral_num']
                ));
                # 积分,金币 记录
                # 打劫人
                MemberService::addLog_gold($this->code, $robberyInfo['gold_num'], 12, $robberyInfo['robbed_code']);
                MemberService::addLog_income($this->code, $robberyInfo['gold_num'], 5, 8);
                MemberService::addLog_integral($this->code, $robberyInfo['integral_num'], 1, 9, $robberyInfo['robbed_code']);
                # 被打劫人
                MemberService::addLog_gold($robberyInfo['robbed_code'], $robberyInfo['gold_num'], 14, $this->code);
                MemberService::addLog_integral($robberyInfo['robbed_code'], $robberyInfo['integral_num'], 2, 10, $this->code);
                # 更新redis
                # 打劫人
                $this->memberInfo['gold'] = priceFormat($this->memberInfo['gold'] + $robberyInfo['gold_num']);
                $this->memberInfo['income'] = priceFormat($this->memberInfo['income'] + $robberyInfo['gold_num']);
                $this->memberInfo['integral'] = priceFormat($this->memberInfo['integral'] + $robberyInfo['integral_num']);
                # 被打劫人
                $robbedMember = $redis->hGetJson('memberInfo', $robberyInfo['robbed_code']);
                $robbedMember['gold'] = priceFormat($robbedMember['gold'] - $robberyInfo['gold_num']);
                $robbedMember['integral'] = priceFormat($robbedMember['integral'] - $robberyInfo['integral_num']);
                # 更新
                $redis->hSetJson('memberInfo', $this->code, $this->memberInfo);
                $redis->hSetJson('memberInfo', $robberyInfo['robbed_code'], $robbedMember);
            }
            # 打劫人清空
            $redis->hDel('Robbery', $this->code);
            # 被打劫清除
            $robbedInfo = $redis->hGetJson('Robbed', $robberyInfo['robbed_code']);
            unset($robbedInfo[$this->code]);
            if (empty($robbedInfo)) {
                $redis->hDel('Robbed', $robberyInfo['robbed_code']);
            } else {
                $redis->hSetJson('Robbed', $robberyInfo['robbed_code'], $robbedInfo);
            }
            $time = strtotime(date('Y-m-d 23:59:59')) - time();
            # 每天最多打劫 五个人
            $robbingFive = $redis->hGetJson('robbingFive', $this->code);
            if (empty($robbingFive)) {
                $robbingFive = array();
            }
            if (!in_array($robberyInfo['robbed_code'], $robbingFive)) {
                array_push($robbingFive, $robberyInfo['robbed_code']);
                $redis->hSetJson('robbingFive', $this->code, $robbingFive, $time);
            }
            # 每天连续打劫一个人 最多 两次
            $continuous = $redis->hGet('continuous', $this->code . "-" . $robberyInfo['robbed_code']);
            if (!empty($continuous)) {
                $continuous += 1;
                $redis->hSet('continuous', $this->code . "-" . $robberyInfo['robbed_code'], $continuous, $time);
            }
            # 每个人每天最多被打劫五次
            $robbedFive = $redis->hGet('robbedFive', $robberyInfo['robbed_code']);
            if (!empty($robbedFive)) {
                $robbedFive += 1;
                $redis->hSet('robbedFive', $robberyInfo['robbed_code'], $robbedFive, $time);
            }
            # 完成任务=>打劫玩家
            TaskService::finishTask($this->code, 15);
            return array('status' => true, 'msg' => '操作成功');
        } else {
            return array('status' => false, ' msg' => '参数为空');
        }
    }

    /**
     * @return array
     * @content 停止打劫
     */
    function robberyStop()
    {
        # 停止打劫
        $info = input('post.');
        $redis = new Redis();
        # 打劫人
        $redis->hDel('Robbery', $info['member_code']);
        # 被打劫
        $robbedInfo = $redis->hGetJson('Robbed', $info['member_code']);
        unset($robbedInfo[$info['robbed_code']]);
        if (empty($robbedInfo)) {
            $redis->hDel('Robbed', $info['robbed_code']);
        } else {
            $redis->hSetJson('Robbed', $info['robbed_code'], $robbedInfo);
        }
        return array('status' => true, 'msg' => '已停止打劫');
    }

    /**
     * @return array
     * @throws \think\Exception
     * @content 立即驱逐
     */
    function expel()
    {
        # 立即驱逐
        $info = input('post.');
        $redis = new Redis();
        # 打劫人
        $robberyInfo = $redis->hGetJson('Robbery', $info['member_code']);
        # 被打劫
        $robbedInfo = $redis->hGetJson('Robbed', $this->code);
        # 修改状态
        # 打劫人
        $robberyInfo[$info['member_code']]['status'] = 2;
        # 被打劫人,删除打劫
        unset($robbedInfo[$info['member_code']]);
//        $robbedInfo = array_shift($robbedInfo);
        # 修改redis
        $redis->hSetJson('Robbery', $info['member_code'], $robberyInfo);
        if (empty($robbedInfo)) {
            $redis->hDel('Robbed', $this->code);
        } else {
            $redis->hSetJson('Robbed', $this->code, $robbedInfo);
        }
        # 驱逐成功,给自己加金币 , 3金币
        $res = Db::table('member_property')->where(array('member_code' => $info['robbed_code']))->setInc('gold', 3);
        Db::table('member_property')->where(array('member_code' => $info['robbed_code']))->setInc('income', 3);
        # 打劫失败,扣除打劫人的金币 3个
        $res = Db::table('member_property')->where(array('member_code' => $info['member_code']))->setDec('gold', 3);
        if ($res) {
            # 添加金币记录
            MemberService::addLog_gold($info['member_code'], 3, 13, $robberyInfo['robbed_code']);
            # 修改redis
            $memberRobbey = $redis->hGetJson('memberInfo', $info['member_code']);
            $memberRobbey['gold'] = priceFormat($memberRobbey['gold'] - 3);
            $redis->hSetJson('memberInfo', $info['member_code'], $memberRobbey);
        }
        if ($res) {
            # 添加打劫记录
            Db::table('log_rob')->insert(array(
                'member_code' => $info['member_code'],
                'robbed_code' => $info['robbed_code'],
                'create_time' => $info['create_time'],
                'against_time' => date("Y-m-d H:i:s"),
                'status' => 2,
                'gold_num' => 3
            ));
            # 添加金币记录
            MemberService::addLog_gold($info['robbed_code'], 3, 11, $info['member_code']);
            MemberService::addLog_income($info['robbed_code'], 3, 5, 9);
            # 修改redis
            $robberyMember = $redis->hGetJson('memberInfo', $info['robbed_code']);
            $robberyMember['gold'] = priceFormat($robberyMember['gold'] + 3);
            $robberyMember['income'] = priceFormat($robberyMember['income'] + 3);
            $redis->hSetJson('memberInfo', $info['robbed_code'], $robberyMember);
        }
        # 完成任务=>反击玩家
        TaskService::finishTask($this->code, 16);
        return array('status' => true, 'msg' => '驱逐成功');
    }

    /**
     * @return array
     * @content  查询被打劫的信息
     */
    function robbedInfo()
    {
        # 查询打劫我的所有人信息
        $redis = new Redis();
        $info = $redis->hGetJson('Robbed', $this->code);
        if (!empty($info)) {
            return array('status' => true, 'msg' => '正在被打劫', 'info' => reset($info));
        } else {
            return array('status' => false, 'msg' => '没有被打劫');
        }
    }

    /**
     * @return array
     * @content 查询打劫状态
     */
    function checkRobberyStatus()
    {
        # 查询我正在打劫的状态
        $redis = new Redis();
        $info = $redis->hGetJson('Robbery', $this->code);
        if (!empty($info)) {
            # 判断状态
            if ($info[$this->code]['status'] == 0) {
                $status = '正在打劫中';
            } elseif ($info[$this->code]['status'] == 1) {
                $status = '打劫成功';
            } else {
                $status = '打劫失败';
            }
            return array('status' => true, 'msg' => $status, 'info' => $info[$this->code], 'robberyStatus' => $info[$this->code]['status']);
        } else {
            return array('status' => false, 'msg' => '没有正在打劫的玩家');
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 开始打劫
     */
    function startRobbing()
    {
        $info = input('post.');
        if (!empty($info['p_code'])) {
            #redis
            $redis = new Redis();
            $time = strtotime(date('Y-m-d 23:59:59')) - time();
            # 每天最多打劫 五个人
            $robbingFive = $redis->hGetJson('robbingFive', $this->code);
            if (empty($robbingFive)) {
                # 查询今天的打劫人数
                $robbingFive = Db::table('log_rob')
                    ->field('distinct robbed_code')
                    ->where(array('member_code' => $this->code))
                    ->where("date(create_time) = '" . date('Y-m-d') . "'")
                    ->select();
                $robbingFive = array_column($robbingFive, 'robbed_code');
                $redis->hSetJson('robbingFive', $this->code, $robbingFive, $time);
            }
            if (count($robbingFive) >= 5) {
                return array('status' => false, 'msg' => '每天最多打劫五个人');
            }
            # 每天连续打劫一个人 最多 两次
            $continuous = $redis->hGet('continuous', $this->code . "-" . $info['p_code']);
            if (empty($continuous)) {
                # 查询今天 连续打劫此人的次数
                $continuous = Db::table('log_rob')
                    ->where(array('member_code' => $this->code, 'robbed_code' => $info['p_code']))
                    ->where("date(create_time) = '" . date('Y-m-d') . "'")
                    ->count();
                $redis->hSet('continuous', $this->code . "-" . $info['p_code'], $continuous, $time);
            }
            if ($continuous >= 1) {
                return array('status' => false, 'msg' => '每天打劫同一个人最多一次');
            }
            # 每个人每天最多被打劫五次
            $robbedFive = $redis->hGet('robbedFive', $info['p_code']);
            if (empty($robbedFive)) {
                # 查询今天被打劫多少次
                $robbedFive = Db::table('log_rob')
                    ->where(array('robbed_code' => $info['p_code']))
                    ->where("date(create_time) = '" . date('Y-m-d') . "'")
                    ->count();
                $redis->hSet('robbedFive', $info['p_code'], $robbedFive, $time);
            }
            if ($robbedFive >= 5) {
                return array('status' => false, 'msg' => '每人每天最多被打劫五次');
            }
            # 判断打劫人的金币是否足够
            if ($this->memberInfo['gold'] < 3) {
                return array('status' => false, 'msg' => '金币不足, 无法打劫别人');
            }
            # 判断被打劫人的金币是否足够
            $pMemberInfo = $redis->hGetJson('memberInfo', $info['p_code']);
            if (empty($pMemberInfo)) {
                $pMemberInfo = Db::table('member m')
                    ->field('m.*,mp.*,mc.*,ml.title')
                    ->leftJoin('member_property mp', 'mp.member_code=m.code and mp.is_fake=1')
                    ->leftJoin('member_collection mc', 'mc.member_code=m.code')
                    ->leftJoin('member_level ml', 'ml.level=m.level')
                    ->where(array('code' => strtoupper($info['p_code'])))->find();
                # 头像地址
                $pMemberInfo['head_portrait'] = imgurl($pMemberInfo['head_portrait']);
                # 微信收款码
                $pMemberInfo['wx_img'] = imgurl($pMemberInfo['wx_img']);
                # 支付宝收款码
                $pMemberInfo['ali_img'] = imgurl($pMemberInfo['ali_img']);
                # 银联收款码
                $pMemberInfo['union_img'] = imgurl($pMemberInfo['union_img']);
                $pMemberInfo['gold'] = priceFormat($pMemberInfo['gold']);
                $pMemberInfo['materials'] = priceFormat($pMemberInfo['materials']);
                $pMemberInfo['integral'] = priceFormat($pMemberInfo['integral']);
                $redis->hSetJson('memberInfo', $info['p_code'], $pMemberInfo);
            }
            if ($pMemberInfo['gold'] < 5 or $pMemberInfo['integral'] < 5) {
                return array('status' => false, 'msg' => '被打劫人金币/积分不足,无法打劫');
            }
            # 被打劫人,先判断是否存在别人正在打劫的
            $robbedInfo = $redis->hGetJson('Robbed', $info['p_code']);
            if (empty($robbedInfo)) {
                $robbedInfo = array();
            }
            if (count($robbedInfo) >= 2) {
                return array('status' => false, 'msg' => '正在被打劫,不可进行打劫了');
            }
            # 确定打劫成功获得的金币/积分
            $goldNum = rand(2, 4);
            $integralNum = rand(2, 4);
            if (count($robbedInfo) == 1) {
                $first = reset($robbedInfo);
                # 不是一个人打劫, 需要判断被打劫人的金币/积分 余额 ,
                if (($pMemberInfo['gold'] - $first['gold_num']) < $goldNum) {
                    $goldNum = $pMemberInfo['gold'] - $first['gold_num'];
                }
                if (($pMemberInfo['integral'] - $first['integral_num']) < $integralNum) {
                    $integralNum = $pMemberInfo['integral'] - $first['integral_num'];
                }
            }
            $arr = array(
                'member_code' => $this->code,
                'member_name' => $this->memberInfo['name'],
                'member_headPortrait' => $this->memberInfo['head_portrait'],
                'robbed_code' => $info['p_code'],
                'create_time' => date("Y-m-d H:i:s"),
                'status' => 0,
                'gold_num' => $goldNum,
                'integral_num' => $integralNum
            );
            $robberyArr = array($this->code => $arr);
            # 被打劫
//            if (!empty($robbedInfo)) {
            $robbedInfo[$this->code] = $arr;
//            }
            # 存入redis
            $redis->hSetJson('Robbery', $this->code, $robberyArr, 180);//180
            $redis->hSetJson('Robbed', $info['p_code'], $robbedInfo, 90);//90
            # 通知被打劫人
            $getui = new IGeTuiService();
            $getui->pushMessageToSingle('被打劫', '正在被打劫', $this->memberInfo['name'] . '正在打劫你,立即驱逐', $info['p_code'], 2);
            return array('status' => true, 'msg' => '正在打劫中', 'info' => $arr);
        } else {
            return array('status' => false, 'msg' => '被打劫人信息为空');
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询当前不在线玩家(积分/金币 大于5 的)
     */
    function nonOnline()
    {
        # 查询不在线玩家
        $nonOnlineList = Db::table('member m')
            ->field('m.name,(select  COALESCE(sum(earnings_price),0) from member_business mb where mb.member_code = m.code and mb.status != -1 and place_status=1) combat_power,m.code,head_portrait')
            ->leftJoin('member_property mp', 'm.code=mp.member_code and is_fake=1')
            ->where('(' . time() . '-UNIX_TIMESTAMP((select change_time from log_login ll where ll.member_code=m.code order by id desc limit 1)))>=3600')
            ->where("type != 3 and type != 4")
            ->where("mp.gold >=5 and mp.integral >=5")
            ->where("m.code != '" . $this->code . "'")
            ->group('m.code')
            ->limit(10)
            ->select();
        if (!empty($nonOnlineList)) {
            foreach ($nonOnlineList as $k => $v) {
                $nonOnlineList[$k]['head_portrait'] = imgUrl($v['head_portrait']);
                $nonOnlineList[$k]['combat_power'] = priceFormat($v['combat_power']);
            }
        }
        return array('status' => true, 'msg' => '查询成功', 'info' => $nonOnlineList);
    }
}